package kk.service.impl;

import kk.dao.UserDao;
import kk.dao.impl.UserDaoImpl;
import kk.domain.PageBean;
import kk.domain.User;
import kk.service.UserService;
import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoImpl();

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    /**
     * 添加用户
     * @param user
     */
    @Override
    public void add(User user) {
        userDao.add(user);
    }

    /**
     * 根据id删除用户
     * @param id
     */
    @Override
    public void deleteUserById(int id) {
        userDao.deleteUserById(id);
    }

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    @Override
    public User findUserById(int id) {
        return userDao.findUserById(id);
    }

    /**
     * 修改用户
     * @param user
     */
    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    /**
     * 删除选中用户
     * @param uids
     */
    @Override
    public void delSelectedUser(String[] uids) {
        if(uids!=null && uids.length>0){
            //遍历数组
            for (String uid : uids) {
                //调用userDao的根据id删除单个用户
                userDao.deleteUserById(Integer.parseInt(uid));
            }
        }
    }

    /**
     * 根据条件分页查询用户
     * @param _currentPage
     * @param _rows
     * @param condition
     * @return
     */
    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
        PageBean<User> pb=new PageBean<User>();
        int rows=Integer.parseInt(_rows);
        //调用dao查询totalCount
        int totalCount = userDao.findTotalCount(condition);
        //设置总记录数
        pb.setTotalCount(totalCount);
        //计算总页数
        int totalPage=(totalCount % rows == 0) ? (totalCount/rows) : (totalCount/rows+1);
        //设置总页数
        pb.setTotalPage(totalPage);
        int currentPage=Integer.parseInt(_currentPage);
        //对currentPage进行判断
        if(currentPage<=0){
            currentPage=1;
        }
        if (currentPage>totalPage){
            currentPage=totalPage;
        }
        //设置当前页码
        pb.setCurrentPage(currentPage);
        //设置每页显示条数
        pb.setRows(rows);

        //计算从哪里开始查询
        int start = (currentPage-1)*rows;
        //调用dao查询list集合
        List<User> list = userDao.findUserByPage(start,rows,condition);
        //设置list
        pb.setList(list);
        //返回pb
        return pb;
    }

}
